import { Component, Input } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { NetProvider } from '../../providers/net/net';
import { GlobalsProvider } from '../../providers/globals/globals';
import { LoginPage } from '../login/login';

/**
 * Generated class for the TaskListPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-task-list',
  templateUrl: 'task-list.html',
})
export class TaskListPage {
  @Input() public title: string = "在线任务";
  private businessType: string;
  private businessTypes: any = [];
  private tasks: any[] = [];
  private timers: number[] = [];
  private didLoaded: boolean = false;
  private selectOptions: any = {
    title: "选择业务类型",
    mode: "md"
  };

  constructor(public navCtrl: NavController, public navParams: NavParams, public net: NetProvider, private globals: GlobalsProvider) {
  }

  ionViewDidLoad() {
    this.init();
  }

  init() {
    let me = this;
    me.net.postJson(me.globals.urls.enums, { enumname: "BusinessType" }, (response) => {
      if (response && response.code) {
        if (response.code == "200") {
          me.businessTypes = [];
          for (let key in response.data) {
            let val = response.data[key];
            me.businessTypes.push({ key: key, val: val });
          }
          let defaultKey = me.businessTypes[0]["key"];
          me.businessType = defaultKey;
          me.didLoaded = true;
          me.load();
          me.timers.push(setInterval(() => { me.load(); }, 3000));
        } else if (response.code == "401") {
          me.globals.navControl.setRoot(LoginPage);
        }
      }
    }, (xhr) => {

    });
  }

  ionViewDidEnter() {
    if (this.timers.length > 0) {
      this.load();
    } else if (this.didLoaded) {
      this.load();
      this.timers.push(setInterval(() => { this.load(); }, 3000));
    }
  }

  ionViewDidLeave() {
    this.clearTimer();
  }

  clearTimer() {
    while (this.timers.length > 0) {
      let timer: number = this.timers.pop();
      clearInterval(timer);
    }
  }

  select() {
    this.load();
  }

  load() {
    let me = this;
    switch (me.businessType) {
      case "IntraCityDistribution":
        me.net.postJson(me.globals.urls.intraCityDistributionQuery, {}, (response) => {
          if (response && response.code) {
            if (response.code == "200") {
              me.tasks = response["data"].list;
            } else if (response.code == "401") {
              me.globals.navControl.setRoot(LoginPage);
            }
          }
        }, (xhr) => {
        });
        break;
      default:
        this.tasks = [];
        break;
    }
  }

  push(item) {
    console.log(item);
  }

}
